/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.ainlolcat.ainscience.entity;

import java.util.*;

import org.ainlolcat.ainscience.Controller;
import org.ainlolcat.ainscience.UpdateListener;
import org.ainlolcat.ainscience.column.Column;
import org.ainlolcat.ainscience.entity.links.Link;
import org.ainlolcat.ainscience.matrix.Matrix;
import org.ainlolcat.ainscience.templates.Template;
import org.ainlolcat.ainscience.tools;
import org.apache.log4j.Logger;
import org.jdom.Element;

/**
 *
 * @author ain
 */
public class SimpleEntity extends AbstractEntity implements UpdateListener{
    private static Logger log = Logger.getLogger(SimpleEntity.class);

    private Integer matrixNum;
    private Element description;
    Hashtable<String,Link> links;
    private String filename;

    public SimpleEntity(Template template, String type){
        this.template = template;
        this.type = type;
        ID = tools.generateID();
        links = new Hashtable<String, Link>();
    }

    public SimpleEntity(Element description){
        this.description = description;
        String e_template_name = description.getAttributeValue("templateName");
        template =  Controller.getInstance().getProject().getTemplateByName(e_template_name);
        type = description.getAttributeValue("entityType");
        ID = tools.generateID();
        links = new Hashtable<String, Link>();
        Controller.getInstance().addUpdateListener(this);
    }

    public EntityParser getParser() {
        return new SimpleEntityParser();
    }

    public Link getLink(String name) {
        return links.get(name);
    }

    public void setLink(Link link) {
        links.put(link.getName(),link);
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public Integer getMatrixNum() {
        return matrixNum;
    }

    public void setMatrixNum(Integer matrixNum) {
        this.matrixNum = matrixNum;
    }

    public Collection<Link> getLinks() {
        return links.values();
    }

    public List<String> getDependencies() {
        List<String> ids = new ArrayList<String>();
        for (Link link:links.values()){
            ids.add(link.getL2Entity());
        }
        return ids;
    }

    public void onProjectUpdate(){
        try {
            new SimpleEntityParser().update(this);
        } catch (UnsupportedEntityTypeException e) {
            log.error(e);
        }
        throwUpdateEvent();
    }

    public void onEntityUpdate(Entity entity, int action) {
        if (getDependencies().contains(entity.getName())){
            try {
                new SimpleEntityParser().update(this);
            } catch (UnsupportedEntityTypeException e) {
                log.error(e);
            }
            throwUpdateEvent();
        }
    }
}
